import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatSession, ChatSessionParams } from '@/types/chat';
import { Prisma } from '@prisma/client';

// POST /api/client/chat/sessions/list - 获取聊天会话列表
async function handlePost(request: NextRequest): Promise<ChatSession[]> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析查询参数
  const body: ChatSessionParams = await request.json();
  const search = (body?.search) || '';

  // 4. 构建查询条件
  const where: Prisma.ChatSessionWhereInput = {
    userId: userId,
  };

  // 全局模糊搜索
  if (search) {
    where.OR = [
      { title: { contains: search, } },
      { messages: { some: { content: { contains: search, } } } }
    ];
  }

  // 5. 查询数据
  const sessions = await prisma.chatSession.findMany({
    where,
    include: {
      content: { include: { cover: true } },
      _count: { select: { messages: true } }
    },
    orderBy: [ { updatedAt: 'desc' } ]
  });

  // 6. 数据转换
  return sessions.map(session => ({
    id: session.id,
    chatId: session.chatId,
    title: session.title || '新对话',
    userId: session.userId,
    agentId: session.agentId || '',
    contentId: session.contentId || '',
    createdAt: session.createdAt.toISOString(),
    updatedAt: session.updatedAt.toISOString(),
    messageCount: session._count.messages,
    _count: { messages: session._count.messages },
    content: session.content ? {
      id: session.content.id,
      title: session.content.title,
      content: session.content.content || '',
      coverId: session.content.coverId || '',
      agent: undefined,
      viewCount: session.content.viewCount,
      favoritesCount: session.content.favoritesCount,
      isBanner: !!session.content.isBanner,
      type: session.content.type as any,
      agentId: session.content.agentId || undefined,
      createdAt: session.content.createdAt.toISOString(),
      updatedAt: session.content.updatedAt.toISOString(),
      categories: [],
      cover: session.content.cover ? {
        id: session.content.cover.id,
        url: session.content.cover.url,
        name: session.content.cover.path,
        size: session.content.cover.size,
        type: session.content.cover.mimeType,
        createdAt: session.content.cover.createdAt.toISOString(),
        updatedAt: (session.content.cover.deletedAt || session.content.cover.createdAt).toISOString(),
      } : undefined,
      url: session.content.url || undefined,
    } : undefined,
  }));
}

export const POST = withMiddleware(handlePost);
